﻿using System;
using System.Collections.Generic;
using System.Linq;
using log4net;
using StockFinder.Model;
using StockFinder.NorgatePremiumData;

namespace StockFinder.StockLists.SymbolListEnumerators
{
    public abstract class NorgateOfflinePriceLoaderSymbolListEnumerator : IStockList
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(NorgateOfflinePriceLoaderSymbolListEnumerator)); 
        private int _Index = -1;
        private readonly bool _LoadPrices;
        private Dictionary<Symbol, string> _Symbols;
        private readonly NorgatePremiumDataStockFilePathsExtractor _NorgatePremiumDataStockFilePathsExtractor = new NorgatePremiumDataStockFilePathsExtractor();

        public NorgateOfflinePriceLoaderSymbolListEnumerator(bool loadPrices) { _LoadPrices = loadPrices; }

        public NorgateOfflinePriceLoaderSymbolListEnumerator() : this(true) { }        

        protected abstract Dictionary<Symbol,string> GetSymbols();

        private Dictionary<Symbol, string> Symbols
        {
            get { return _Symbols ?? (_Symbols = GetSymbols()); }
        }

        private Symbol GetCurrentSymbol()
        {
            var symbol = _Symbols.ElementAt(_Index);
            
            try
            {
                if (_LoadPrices)
                {
                    symbol.Key.Prices = _NorgatePremiumDataStockFilePathsExtractor.GetStockPriceHistoryFromFilename(
                        symbol.Value);
                }                
            }
            catch (Exception exception)
            {
                Log.ErrorFormat(exception.ToString());
            }            

            return symbol.Key;
        }

        public Symbol Current
        {
            get
            {
                return GetCurrentSymbol();
            }
        }

        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        public bool MoveNext()
        {
            _Index++;
            return _Index < Symbols.Count;
        }

        public void Reset()
        {
            _Index = -1;
        }

        object System.Collections.IEnumerator.Current
        {
            get { return Current; }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public IEnumerator<Symbol> GetEnumerator()
        {
            return this;
        }

        public int Count
        {
            get
            {
                return Symbols != null ? Symbols.Count : 0;
            }
        }

        public string Name { get; set; }
    }
}
